import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Solution525 {
    public int findMaxLength(int[] nums) {
        Map<Integer, List<Integer>> map=new HashMap<>();
        int cur=0,low=0,high=0;
        List<Integer> zero=new ArrayList<>();
        zero.add(0);
        map.put(0,zero);
        for (int i=0;i<nums.length;i++) {
            cur=cur+(nums[i]==0?-1:1);
            low=Math.min(low,cur);
            high=Math.max(high,cur);
            List<Integer> list=map.getOrDefault(cur,new ArrayList<>());
            list.add(i+1);
            map.put(cur,list);
        }
        int max=0;
        for (int i=low;i<=high;i++){
            if (map.containsKey(i)){
                List<Integer> list=map.get(i);
                max=Math.max(max,list.get(list.size()-1)-list.get(0));
            }
        }
        return max;
    }

    public static void main(String[] args) {
        System.out.println(new Solution525().findMaxLength(new int[]{0,0,1,0,0,0,1,1}));
    }
}
